package com.cskaoyan.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * 自定义的认证器 → 做realm的分发
 * @author stone
 * @date 2022/06/07 09:47
 */
public class MarketAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();
        // 如果认证器设置realm把customRealm、AdminRealm、wxRealm都添加上
        ArrayList<Realm> realms = new ArrayList<>();
        String type = ((MallToken) authenticationToken).getType();
        Iterator<Realm> iterator = originRealms.iterator();
        while (iterator.hasNext()) {
            Realm realm = iterator.next();
            if (realm.getName().toLowerCase().contains(type)) {
                realms.add(realm);
            }
        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
